//
//  GuideViewController.m
//  MagazineShangejie
//
//  Created by mac on 15/1/22.
//  Copyright (c) 2015年 CnbizMedia. All rights reserved.
//

#import "GuideViewController.h"
#import "Util.h"
//#import "MMDrawerController.h"
#import "MainTabBarController.h"
#import "SlideTableViewController.h"
#import "ArticleViewController.h"
#define AddImage(imagexx,imageName) imagexx.image=[UIImage imageNamed:imageName];[scrollView addSubview:imagexx];
#define ImageViewAlloc(x,y,w,h) [[UIImageView alloc]initWithFrame:CGRectMake(x, y, w, h)];
#define labeAlloc(x,y,w,h) [[UILabel alloc]initWithFrame:CGRectMake(x, y, w, h)];
#define BigLabel(uilabel,textxx) uilabel.textAlignment = NSTextAlignmentCenter;uilabel.textColor=[UIColor redColor];uilabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:25];uilabel.text=textxx;[scrollView addSubview:uilabel];

#define SmallLabel(uilabel,textxx) uilabel.textAlignment = NSTextAlignmentCenter;uilabel.textColor=[UIColor blackColor];uilabel.font=[UIFont systemFontOfSize:14];uilabel.text=textxx;[scrollView addSubview:uilabel];



#include <ifaddrs.h>
#include <arpa/inet.h>

@interface GuideViewController ()<UIScrollViewDelegate>{
    UIPageControl*pageControl;
    NSString *IPString;
    
    NSMutableArray *Subscribe;
    
    UIPageControl *pageCtrl;
    
    NSMutableArray *listTop;
}
//@property (nonatomic,strong) MMDrawerController * drawerController;

@end

@implementation GuideViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
 
    
    Subscribe = [[NSMutableArray alloc] init];
    listTop   = [[NSMutableArray alloc]init];

    IPString  = @"60.195.250.90";//北京
//    if (IPString.length > 1) {
        //如果ip不为空才去获取城市列表
        [self getTheAllCity];
//    }
    
        NSDictionary*dict=[NSDictionary dictionaryWithObjectsAndKeys:@"精选",@"catname",@"",@"catdir", nil];
    
    NSArray *loveCityArray = [[NSArray alloc]init];
    [UserDefaults setObject:loveCityArray forKey:@"loveCityArray"];
    
    [Subscribe insertObject:dict atIndex:0];
    
    
    [UserDefaults setValue:Subscribe forKey:@"listTop"];
    
    
    NSArray*imageArray=[NSArray arrayWithObjects:[UIImage imageNamed:@"guidePage1"],[UIImage imageNamed:@"guidePage2"],[UIImage imageNamed:@"guidePage3"],[UIImage imageNamed:@"guidePage4"],[UIImage imageNamed:@"guidePage5"], nil];
    
    self.view.backgroundColor=[UIColor whiteColor];
    UIScrollView*scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.pagingEnabled = YES;
    scrollView.delegate = self;
    scrollView.contentSize = CGSizeMake(scrollView.bounds.size.width * imageArray.count, scrollView.bounds.size.height);
    [self.view addSubview:scrollView];
    
  
    
    NSDictionary *IPDic = [[NSDictionary alloc] initWithObjectsAndKeys:@"113.204.112.162",@"ip", nil];
    NSLog(@"IPDic %@",IPDic );
    //首先获取IP地址
    NSURL *baseURL = [NSURL URLWithString:@"http://ip.taobao.com/"];
    
    
    //首先获取IP地址
    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    [manager GET:@"service/getIpInfo2.php" parameters:@{@"ip": @"myip"} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *IPDic = responseObject[@"data"];
        
        IPString = IPDic [@"ip"];
        
        NSLog(@"IPString11 == %@",IPString);
       
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        
    }];

    
        //将获取的IP地址通过Local/List发送到服务器，然后获取城市列表，将列表获取的城市保存到本地
        //    [[AppAPIClient sharedClient] GET:@"Local/List" parameters:@{@"ip": IPString} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //
        //        NSLog(@"[responseObject == %@",responseObject[@"data"]);
        //
        //
        //        NSDictionary *shujuDic = responseObject[@"data"];
        //        if (shujuDic != NULL) {
        //
        //            NSMutableArray *cityArray = shujuDic[@"cities"];
        //
        //            NSLog(@"  city  array  ==  %@",cityArray);
        //
        //            NSDictionary *theCityDic = [[NSDictionary alloc] init];
        //            for (theCityDic in cityArray) {
        //
        //
        //                //数据可能获取到了，但是界面已经出来了，想想什么界面来刷新界面。
        //                //这里有问题，不知道获取的城市信息是否是正确的，
        //                NSString *cityTurn = theCityDic[@"description"];
        //                if ([cityTurn isEqualToString:@"local"]) {
        //                    dict1 = theCityDic;//获取的城市字典
        //                }
        //            }
        //
        //
        //            NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
        //            [userDefault setObject:cityArray forKey:@"cityArray"];
        //
        //            [userDefault synchronize];//存入数据，单例
        //        }
        
        
        
        //        if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]]){
        //            return ;
        //        }
        //        NSDictionary *Subscribe = [responseObject[@"data"] mutableCopy];
        //        NSDictionary *benDiDic = Subscribe[@"local"];
        //        NSLog(@"benDiDic == %@",benDiDic);
        //        NSString *catname = [benDiDic objectForKey:@"catname"];
        
        
        
        //然后将精选和本地加入到条目中
        //获取的是喜欢的新闻类的列表
        [[AppAPIClient sharedClient] GET:@"Category/Subscribe" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            
            
            
            if (![responseObject[@"data"] isKindOfClass:[NSArray class]]){
                return ;
            }
            Subscribe = [responseObject[@"data"] mutableCopy];
            NSDictionary*dict=[NSDictionary dictionaryWithObjectsAndKeys:@"精选",@"catname",@"",@"catdir", nil];
     
            [Subscribe insertObject:dict atIndex:0];
            
            
            [UserDefaults setValue:Subscribe forKey:@"listTop"];
            NSLog(@"UserDefaults == %@",UserDefaults);
            NSLog(@"Subscribe == %@",Subscribe);
            
            //设置通知，城市已经切换，现在刷新界面
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"showTheNewCity" object:self userInfo:nil ];
            
//            if (IPString.length > 0) {
//
                [UserDefaults setValue:IPString forKey:@"IP"];
            
            IPString = @"60.195.250.90";//北京
            
                //获取的是全部的新闻列表
            [[AppAPIClient sharedClient] GET:@"Category/Index" parameters:@{@"ip":IPString} success:^(AFHTTPRequestOperation *operation, id responseObject) {
                    NSMutableArray *Index = responseObject[@"data"];
                    NSLog(@"index --- %@",Index);
                    
                    
                    
                    
//                    //当用户在没有开通本地栏目的地区，默认加入一个精选
//                    NSDictionary*dict=[NSDictionary dictionaryWithObjectsAndKeys:@"精选",@"catname",@"",@"catdir", nil];
//                    [UserDefaults setValue:dict forKey:@"local"];
//                    
//                    for (cityDic in Index ) {
//                        if ([[cityDic objectForKey:@"description"] isEqualToString:@"local"]) {
//                            [UserDefaults setValue:cityDic forKey:@"local"];
//                            NSLog(@"the cityDic is %@",cityDic);
//                        }
//                    }

                    
                    
                    if([Index isKindOfClass:[NSNull class]] || [Index count] == 0){
                        return;
                    }
                
                    NSMutableArray*listBottom=[Index mutableCopy];
//                    NSMutableArray*listBottom = [[NSMutableArray alloc]init];
                                [listBottom addObjectsFromArray:responseObject[@"data"]];
                    for (NSDictionary*dic in [UserDefaults objectForKey:@"listTop"]) {
                        for (NSDictionary*_dic in listBottom) {
                            if ([dic[@"catname"] isEqualToString:_dic[@"catname"]]) {
                                [listBottom removeObject:_dic];
                                break;
                            }
                        }
                        
                    }
                    [UserDefaults setValue:listBottom forKey:@"listBottom"];
                    NSLog(@"listBottom == %@",listBottom);
                    //            [SVProgressHUD dismiss];
                    
                    
                    //当用户在没有开通本地栏目的地区，默认加入一个精选
                    NSDictionary*dict=[NSDictionary dictionaryWithObjectsAndKeys:@"精选",@"catname",@"",@"catdir", nil];
//                    [UserDefaults setValue:dict forKey:@"local"];
                NSDictionary *quYujjDic = [NSDictionary dictionaryWithObjectsAndKeys:@"\u533a\u57df\u7ecf\u6d4e",@"catname",@"0",@"catid",@"quyujingji",@"catdir",@"",@"items",@"local",@"description",@"",@"image",0, @"sub",nil];
                
//                [listTop insertObject:dict atIndex:0];
                [Subscribe insertObject:quYujjDic atIndex:1];//将这个城市的字典排在数组的第2位
                [UserDefaults setValue:Subscribe forKey:@"listTop"];
                [listBottom removeObject:quYujjDic];
                [UserDefaults setValue:listBottom forKey:@"listBottom"];
                
                [UserDefaults setValue:quYujjDic forKey:@"local"];//这是以前的做法，现在暂时屏蔽，保存的是当前的城市
                NSLog(@"the cityDic is %@",quYujjDic);

//                    for (NSMutableDictionary *cityDic in Index ) {
//
//                        if ([[cityDic objectForKey:@"description"] isEqualToString:@"local"]) {
//                    
//                            listTop=[Index mutableCopy];
////                            [listTop removeObject:cityDic];
// 
//                            [listTop insertObject:dict atIndex:0];
//                            [listTop insertObject:cityDic atIndex:1];//将这个城市的字典排在数组的第2位
//                            [UserDefaults setValue:listTop forKey:@"listTop"];
//                            [listBottom removeObject:cityDic];
//                            [UserDefaults setValue:listBottom forKey:@"listBottom"];
//                    
//                           [UserDefaults setValue:dict forKey:@"local"];//这是以前的做法，现在暂时屏蔽，保存的是当前的城市
//                            NSLog(@"the cityDic is %@",cityDic);
//                        }
//                    }
                
                    

                } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                    NSLog(@"ERR: %@",operation.responseString);
                    
                }];
//            }
         }
                                 failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                     NSLog(@"ERR: %@",operation.responseString);
                                     
                                 }];
    
    CGSize size = CGSizeMake(100, 40);
    pageControl=[[UIPageControl alloc]initWithFrame:CGRectMake((self.view.frame.size.width-size.width)/2, self.view.frame.size.height - size.height-50, size.width, size.height)];
    pageControl.currentPage = 0;
    pageControl.numberOfPages=imageArray.count;
    pageControl.pageIndicatorTintColor=[UIColor colorWithRed:1.000 green:0.000 blue:0.000 alpha:0.510];
    pageControl.currentPageIndicatorTintColor=[UIColor redColor];
//    [self.view addSubview:pageControl];
    
    CGRect frame=self.view.frame;
    for (int i =0 ; i<imageArray.count; i++) {
        UIImageView*image=[[UIImageView alloc]initWithFrame:CGRectMake(frame.size.width*i, 0, frame.size.width, frame.size.height)];
        image.image=imageArray[i];
        [scrollView addSubview:image];
    }
    UIButton*button=[UIButton buttonWithType:UIButtonTypeCustom];
    [button setFrame:CGRectMake(frame.size.width*(imageArray.count - 1)+(frame.size.width-145)/2, frame.size.height*0.7, 145, 45)];
//    [button setTitle:@"立即打开" forState:UIControlStateNormal];
//    [button setBackgroundColor:[UIColor colorWithRed:0.000 green:0.000 blue:1.000 alpha:0.500]];
//    NSDictionary *attribs = @{NSFontAttributeName: [UIFont fontWithName:@"Helvetica-Bold" size:25],NSForegroundColorAttributeName:[UIColor redColor]};
//    NSMutableAttributedString *attributedText =[[NSMutableAttributedString alloc] initWithString:@"立即打开" attributes:attribs];
//    
//    [button setAttributedTitle:attributedText forState:UIControlStateNormal];
//    button.layer.borderWidth = 0.5;
//    button.layer.borderColor = [[UIColor redColor] CGColor];
//    button.layer.cornerRadius = 22;
//    button.layer.masksToBounds = YES;
    [button addTarget:self action:@selector(MainVC) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:button];
    
}




//IOS获取IP地址
- (NSString *)getIPAddress
{
    NSString *address = @"error";
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    int success = 0;
    
    // retrieve the current interfaces - returns 0 on success
    success = getifaddrs(&interfaces);
    if (success == 0) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while (temp_addr != NULL) {
            if( temp_addr->ifa_addr->sa_family == AF_INET) {
                // Check if interface is en0 which is the wifi connection on the iPhone
                if ([[NSString stringWithUTF8String:temp_addr->ifa_name] isEqualToString:@"en0"]) {
                    // Get NSString from C String
                    address = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)];
                }
            }
            
            temp_addr = temp_addr->ifa_next;
        }
    }
    
    // Free memory
    freeifaddrs(interfaces);
    
    return address;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat pageWidth = scrollView.frame.size.width;
    long int page = floor((scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    pageControl.currentPage = page;
    

    if (page==3) {
        pageControl.alpha=1;
        
    }else{
        pageControl.alpha=1;
    }
    
    
}

//-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
//    
//}

-(void)MainVC{
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    MainTabBarController*MainTabBar=[story instantiateViewControllerWithIdentifier:@"MainTabBarController"];
    MainTabBar.view.backgroundColor=[UIColor orangeColor];
    MainTabBar.view.window.backgroundColor=[UIColor whiteColor];
//    SlideTableViewController*slide=[story instantiateViewControllerWithIdentifier:@"SlideTableViewController"];
//    
//    self.drawerController = [[MMDrawerController alloc]
//                             initWithCenterViewController:MainTabBar
//                             leftDrawerViewController:nil
//                             rightDrawerViewController:slide];
//    [self.drawerController setRestorationIdentifier:@"MMDrawer"];
//    
//    
//    [self.drawerController setMaximumRightDrawerWidth:self.view.frame.size.width*0.6];
//    
//    [self.drawerController setCloseDrawerGestureModeMask:MMCloseDrawerGestureModeAll];
//    
//    [self.drawerController
//     setDrawerVisualStateBlock:^(MMDrawerController *drawerController, MMDrawerSide drawerSide, CGFloat percentVisible) {
//         MMDrawerControllerDrawerVisualStateBlock block;
//         
//         if(block){
//             block(drawerController, drawerSide, percentVisible);
//         }
//     }];
    self.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:MainTabBar animated:YES completion:nil];
    //    [self.view addSubview:self.drawerController.view];
    //    [self addChildViewController:self.drawerController];
}

- (void)getTheAllCity
{
    //@{@"ip": [UserDefaults objectForKey: @"IP"]}
    
    [[AppAPIClient sharedClient] GET:@"Local/List" parameters:@{@"ip": IPString} success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"++++ responseObject ++++ %@",responseObject);
        if ([responseObject [@"code"] integerValue] == 1) {
        NSMutableArray *cityArray = [NSMutableArray  arrayWithArray:responseObject[@"data"] [@"cities"] ];
        NSLog(@"++++ cityArray ++++ %@",cityArray);
        
        NSMutableArray *firstArray = [[NSMutableArray alloc] init];
        
        NSString *nowCityNameStr = [UserDefaults objectForKey:@"nowTheCity"];
        NSMutableDictionary *cityNameDic = [[NSMutableDictionary alloc] init];
//        for (  cityNameDic in cityArray ) {
//            
//            NSString  *catName = cityNameDic[@"catname"];
//            [firstArray addObject:catName];
//            
//            //判断roadTitleLab.text 是否含有qingjoin
//            if([nowCityNameStr rangeOfString:catName].location !=NSNotFound)//_roaldSearchText
//            {
//                
//                [listTop insertObject:cityNameDic atIndex:0];
//                 [UserDefaults setValue:cityNameDic forKey:@"local"];
//                NSLog(@"yes");
//            }
//            else
//            {
//                NSDictionary *quYujjDic = [NSDictionary dictionaryWithObjectsAndKeys:@"\u533a\u57df\u7ecf\u6d4e",@"catname",@"0",@"catid",@"quyujingji",@"catdir",@"",@"items",@"local",@"description",@"",@"image",0, @"sub",nil];
//                [UserDefaults setValue:quYujjDic forKey:@"local"];
//                [listTop insertObject:quYujjDic atIndex:0];
//                NSLog(@"no");
//            }
//        }
        
            
            
            
            
            //        cityArray = [NSArray arrayWithArray:firstArray];
            
            NSLog(@"++++ cityArray ++++ %@",firstArray);
            [UserDefaults setObject:firstArray forKey:@"allCityNameArray"];
            [UserDefaults setObject:cityArray forKey:@"cityNameArray"];
            
            
            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        
    }];
    
}
@end
